﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ATM_Pro.Module;
using System.IO;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Timers;

namespace ATM_Pro
{
    #region  定义枚举

    /// <summary>
    /// 摄像机编号
    /// </summary>
    /// 摄像机的编号如有变化 AnalyzTransImgFileName
    public enum CameraNumber
    {
        水平 = 0,
        垂直 = 1,
        全景 = 2
    }

    /// <summary>
    /// 数据包类型
    /// </summary>
    public enum PacketType
    {
        AlarmMessage = 1,
        AlarmCallBack = 2,
        TradeMessage = 3,
        RealtimeMessage = 4
    }

    /// <summary>
    /// 地点编号
    /// </summary>
    public enum AtmAddress
    {
        SouthGate = 0,
        NorthGate = 1
        //......
    }

    /// <summary>
    /// 报警信息类型
    /// </summary>
    public enum WarnType
    {
        KeyboardException = 0,
        HangoverException = 1
        //......
    }

    /// <summary>
    /// 摄像机状态信息
    /// </summary>
    public enum CameraStateType
    {
        异常 = 0,
        正常 = 1
    }

    #endregion

    public class ImageHandle
    {

        public ImageHandle()
        {

        }

        //generate image's save path
        public static string GenerateSavePath(ATM atm, DateTime dtime, int count, int cur)
        {
            Properties.Settings setting = Properties.Settings.Default;
            string path = string.Format(setting.OutputPath + "\\{0}\\{1}\\{2}\\{3}\\{4}\\{5}",
                              atm.ID.ToString("d2"),
                              atm.Cam.ID.ToString("d2"),
                              Enum.GetName(typeof(PacketType), atm.Cam.InforType) + ((cur == 2) ? "" : ((cur == 0) ? "\\" + Properties.Settings.Default.BigImg : "\\" + Properties.Settings.Default.FaceImg)),
                              dtime.Year.ToString("d2") + dtime.Month.ToString("d2") + dtime.Day.ToString("d2"),
                              dtime.Hour.ToString("d2"),
                              dtime.Minute.ToString("d2"));

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            return Path.Combine(path, string.Format("{0}-{1}.jpg",
                                   dtime.Year.ToString("d2") + dtime.Month.ToString("d2") + dtime.Day.ToString("d2") + dtime.Hour.ToString("d2") + dtime.Minute.ToString("d2") + dtime.Second.ToString("d2"),
                                   count.ToString("d4")));
        }

        //生成文件路径 保存到目标文件夹的根目录
        public static string GenerateSavePath(DateTime dTime)
        {
            string rootSavePath = Properties.Settings.Default.OutputPath;
            if (!Directory.Exists(rootSavePath))
                Directory.CreateDirectory(rootSavePath);
            return Path.Combine(rootSavePath, string.Format("{0}-{1}.jpg",
                                   dTime.Year.ToString("d2") + dTime.Month.ToString("d2") + dTime.Day.ToString("d2") + dTime.Hour.ToString("d2") + dTime.Minute.ToString("d2") + dTime.Second.ToString("d2"),
                                  dTime.Millisecond.ToString("d3")));
        }

        //filename is correct 
        public static bool IsCorrectImgFile(string fileName)
        {
            Regex fileNameRegex = new Regex("\\d{14}-\\d{4}.jpg");
            Match m = fileNameRegex.Match(fileName);
            return m.Success;
        }

        //Screening the image file path
        public void ScreeningExitsFile(string imgFile)
        {
            int length = imgFile.Length;
            string path = imgFile.Substring(0, length - 26);
            string fileName = imgFile.Substring(length - 26, length);
        }


        //分组显示报警信息  找到报警实时录像图片
        public static string AnalyzLiveImgFileName(string p)
        {
            string path = p.Replace(Enum.GetName(typeof(PacketType), 1), Enum.GetName(typeof(PacketType), 4));
            string dir = path.Substring(0, path.Length - 23);
            string fileName = path.Substring(path.Length - 23, 23);
            string res = "";
            if (!File.Exists(dir))
            {
                if (Directory.Exists(dir))
                {
                    string[] files = Directory.GetFiles(dir);
                    foreach (string file in files)
                    {
                        string name = file.Substring(file.Length - 23, 23);
                        if (ImageHandle.IsCorrectImgFile(name))
                        {
                            if (name.StartsWith(fileName.Substring(0, fileName.Length - 8)))
                            {
                                res = file;
                                break;
                            }
                            else
                            {
                                res = "";
                            }
                        }
                    }
                }
            }
            else
            {
                res = dir;
            }
            return res;
        }

        #region
        //分组显示报警信息  找到交易图片
        public static string AnalyzTransImgFileName(string p) //找到最近的一次交易信息 未测试
        {
            string res = "";
            if (File.Exists(p))
            {
                string fileName = Path.GetFileName(p);  //20091014171005-0004.jpg
                int year = Convert.ToInt32(fileName.Substring(0, 4));
                int month = Convert.ToInt32(fileName.Substring(4, 2));
                int day = Convert.ToInt32(fileName.Substring(6, 2));
                int hour = Convert.ToInt32(fileName.Substring(8, 2));
                int minute = Convert.ToInt32(fileName.Substring(10, 2));
                int second = Convert.ToInt32(fileName.Substring(12, 2));
                DateTime dtime = new DateTime(year, month, day, hour, minute, second);
                //p =  D:\ImageOutput\00\01\AlarmMessage\20091015\08\50\20091015085047-0031.jpg

                string path = p.Replace(((int)CameraNumber.垂直).ToString("d2") + "\\" + Enum.GetName(typeof(PacketType), 1), ((int)CameraNumber.水平).ToString("d2") + "\\" + Enum.GetName(typeof(PacketType), 3) + "\\" + Properties.Settings.Default.BigImg);
                //path = D:\ImageOutput\00\00\TradeMessage\BigImg\20091015\08\50\20091015085047-0031.jpg
                string dir = path.Substring(0, path.Length - fileName.Length);//dir = D:\ImageOutput\00\00\TradeMessage\BigImg\20091015\08\50\
                string haspath = dir.Substring(0, path.Length - (fileName.Length + 15));

                if (!Directory.Exists(haspath))
                {
                    res = "没有可搜索路径！";
                    return "";
                }
                else
                {
                    string[] directoryInfo = Directory.GetDirectories(haspath);
                    if (directoryInfo.Length == 0)
                    {
                        res = "没有可搜索路径！";
                        return "";
                    }
                    else
                    {
                        DateTime minTime = ImageHandle.GetMinTime(directoryInfo);
                        while (true)
                        {
                            if (dtime < minTime)
                            {
                                res = "没有可查找路径！";
                                return "";
                            }
                            //当前文件夹存在图片的情况
                            if (Directory.Exists(dir))
                            {
                                string[] files = Directory.GetFiles(dir);
                                if (files.Length == 1)
                                {
                                    if (ImageHandle.IsCorrectImgFile(Path.GetFileName(files[files.Length - 1])))
                                    {
                                        res = files[files.Length - 1];
                                    }
                                }
                                else if (files.Length >= 2)
                                {
                                    foreach (string file in files)
                                    {
                                        string name = file.Substring(file.Length - 23, 23);
                                        if (ImageHandle.IsCorrectImgFile(name))
                                        {
                                            res = file;
                                            break;
                                        }
                                    }
                                }
                                if (res != "") break;
                            }
                            string temp = dir;
                            temp = temp.Substring(0, path.Length - (fileName.Length + 15)); //temp = D:\ImageOutput\00\00\TradeMessage\BigImg\
                            dtime = dtime.AddMinutes(-1);
                            dir = temp + dtime.Year.ToString("d4") + dtime.Month.ToString("d2") + dtime.Day.ToString("d2") + "\\" + dtime.Hour.ToString("d2") + "\\" + dtime.Minute.ToString("d2") + "\\";
                        }
                    }
                }
            }
            else
            {
                res = "";
            }

            return res;
        }

        #endregion


        private static DateTime GetMinTime(string[] directories)
        {
            int[] temp = new int[directories.Length];
            for (int i = 0; i < directories.Length; i++)
            {
                try
                {
                    int dir = Convert.ToInt32(directories[i].Substring(directories[i].Length - 8, 8));
                    temp[i] = dir;
                }
                catch (FormatException fe)
                {
                    temp[i] = 0;
                    Console.WriteLine(fe.Message);
                }
            }
            Array.Sort(temp);
            string timestr = temp[0].ToString();
            return new DateTime(Convert.ToInt32(timestr.Substring(0, 4)), Convert.ToInt32(timestr.Substring(4, 2)), Convert.ToInt32(timestr.Substring(6, 2)), 00, 00, 00);
        }
    }
}